const DB = require('../../utils/db');
module.exports = {
	list: async (acticleId) => {
		// 评论数
		let [totalList] = await DB.query('select count(1) as total from t_comment where acticleId=?', [acticleId]);

		// 查询
		let [list] = await DB.query(
			`select c.id,c.acticleId,c.userId,c.content,c.toUserId,c.toUsername,c.toAvatar,c.isShow,
                  c.commentId, TIMESTAMPDIFF(SECOND, c.createtime, NOW()) AS time,u.username,u.avatar from t_comment c 
                  left join t_user u on c.userId = u.id 
                  where c.acticleId=? and c.commentId is null and u.type=1 order by c.createtime desc`,
			[acticleId]
		);

		for (let key of list) {
			let [list1] = await DB.query(`select c.id,c.acticleId,c.userId,u.username,u.avatar,c.content,c.toUserId,c.toUsername,c.toAvatar,c.isShow,
                  c.commentId, TIMESTAMPDIFF(SECOND, c.createtime, NOW()) AS time from t_comment c 
                  left join t_user u on c.userId = u.id 
                  where ${key.id}= c.commentId and u.type=1 order by c.createtime desc`);
			key.children = list1;
		}

		return { list, total: totalList[0].total };
	},
	add: async (acticleId, userId, username, avatar, content, toUserId, toUsername, toAvatar, commentId, type) => {
		// 添加一级评论
		if (type == 1) {
			await DB.query(`insert into t_comment (acticleId,userId,username,avatar,content) values(?,?,?,?,?)`, [acticleId, userId, username, avatar, content]);
		} else if (type == 2) {
			await DB.query(`insert into t_comment (acticleId,userId,username,avatar,content,toUserId, toUsername, toAvatar, commentId) values(?,?,?,?,?,?,?,?,?)`, [
				acticleId,
				userId,
				username,
				avatar,
				content,
				toUserId,
				toUsername,
				toAvatar,
				commentId
			]);
		}
	}
};
